import frappe
from frappe import _
import json


@frappe.whitelist()
def batch_copy_items(doc, child_rows, row_idx=1):
    """
    由销售订单表头客户+季节，明细行 款名+材质+颜色匹配物料号
    """

    if isinstance(doc, str):
        doc = frappe.get_doc(json.loads(doc))
        child_rows = json.loads(child_rows)
    if isinstance(row_idx, str):
        row_idx = int(row_idx)

    # 如果明细行无style字段，且单据明细行与复制粘贴明细行数一致，则是单独复制某一列
    if (not child_rows[0].get("style") and len(doc.items) == len(child_rows)):
        for row, child_row in zip(doc.items, child_rows):
            row.update(child_row)
        return doc

    # 支持多次追加复制    
    doc.items = doc.items[0:len(doc.items)-len(child_rows)]
    # excel表中的style实际上是物料主数据中的style_name
    item_list = frappe.get_all("Item", 
        filters = {
            "disabled": 0,
            "is_sales_item": 1,
            "shoe_customer": doc.customer,
            "style_name": ("in", {r.get('style') for r in child_rows})
        },
        fields = ["name as item_code", "style", "style_name", "shoe_material", "color", "item_name", "stock_uom as uom"]
    )
    # season 不是物料的属性了
    key_item_dict_map = {(r.style_name, r.shoe_material, r.color): r for r in item_list}

    for r in child_rows:
        key = (r.get('style'), r.get('shoe_material'), r.get('color'))
        item_dict = key_item_dict_map.get(key)
        if item_dict:
            r.update(item_dict)
            r["conversion_factor"] = 1
        elif r.get('style'):
            frappe.msgprint("{0} not in item master".format(key))
        doc.append('items', r)

    return doc